package com.atguigu.collect.service.impl;

import com.atguigu.clients.ProductClient;
import com.atguigu.collect.mapper.CollectMapper;
import com.atguigu.collect.service.CollectService;
import com.atguigu.param.ProductCollectParam;
import com.atguigu.pojo.Collect;
import com.atguigu.utils.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.CollateExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName:CollectServiceImpl
 * Package:com.atguigu.collect.service.impl
 * Description:
 *
 * @Author 应永豪
 * @Create 2024/4/22 16:36
 * @Version 1.0
 */
@Service
@Slf4j
public class CollectServiceImpl implements CollectService {

    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private ProductClient productClient;
    @Override
    public R save(Collect collect) {
//      先查询是否存在
        QueryWrapper<Collect> collectQueryWrapper = new QueryWrapper<>();
        collectQueryWrapper.eq("user_id",collect.getUserId())
                .eq("product_id",collect.getProductId());

        Long count = collectMapper.selectCount(collectQueryWrapper);


        if (count>0){
            return R.fail("收藏已经添加，无需重复添加");
        }

//        不存在则添加
        collect.setCollectTime(System.currentTimeMillis());
        int rows = collectMapper.insert(collect);
        log.info("CollectServiceImpl.save业务执行完毕，结果为:{}",rows);
        return R.ok("添加成功");
    }

    @Override
    public R list(Integer userId) {
        QueryWrapper<Collect> collectQueryWrapper = new QueryWrapper<>();
        collectQueryWrapper.eq("user_id",userId).select("product_id");

        List<Object> idsObject = collectMapper.selectObjs(collectQueryWrapper);

        ProductCollectParam productCollectParam = new ProductCollectParam();

        List<Integer> ids = new ArrayList<>();

        for(Object o : idsObject){
            ids.add((Integer) o);
        }

        productCollectParam.setProductIds(ids);

        R r = productClient.productIds(productCollectParam);
        log.info("CollectServiceImpl.list业务执行完毕，结果为:{}",r);
        return r;
    }

    @Override
    public R remove(Collect collect) {
        QueryWrapper<Collect> collectQueryWrapper = new QueryWrapper<>();
        collectQueryWrapper.eq("user_id",collect.getUserId())
                .eq("product_id",collect.getProductId());

        int rows = collectMapper.delete(collectQueryWrapper);
        log.info("CollectServiceImpl.list业务执行完毕，结果为:{}",rows);
        return R.ok("收藏删除成功");


    }
}
